import { Component, OnInit, Input, OnChanges, SimpleChanges, Output, EventEmitter } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { ChangePasswordBoxService } from './change-password-box.service';
import { LoginService } from 'app/auth/login.service';
import { MessagesService } from 'app/shared/service';
import { sha256 } from 'js-sha256';
import { NotificationService } from 'app/shared/service';

@Component({
    selector: 'itmp-change-password-box',
    templateUrl: './change-password-box.component.html',
    styleUrls: ['./change-password-box.component.css']
})
export class ChangePasswordBoxComponent implements OnInit, OnChanges {
    @Input() isChangePwVisible: boolean;
    @Output() getCrrunKmChange = new EventEmitter<any>();

    isChangePwOkLoading = false;
    validateForm: FormGroup;
    maskStyle = { background: 'rgb(0,0,0,0)' };
    currentUserName: any = '';
    constructor(
        private fb: FormBuilder,
        private changePasswordBoxService: ChangePasswordBoxService,
        public ls: LoginService,
        private msg: MessagesService,
        private message: NotificationService
    ) {}

    // 点击Changepassword选项显示改变密码模态框
    changePassword() {
        this.isChangePwVisible = true;
    }
    // 关闭修改密码模态框
    handleChangePwCancel() {
        this.isChangePwVisible = false;
        this.getCrrunKmChange.emit(this.isChangePwVisible);
    }
    // 向后台提交修改密码表单
    handleChangePwOk() {}
    submitForm(): void {
        // tslint:disable-next-line: forin
        for (const i in this.validateForm.controls) {
            this.validateForm.controls[i].markAsDirty();
            this.validateForm.controls[i].updateValueAndValidity();
        }
        if (!this.validateForm.invalid) {
            const nowData = new Date();
            const timeDe = nowData.getTime();
            const param = {
                userName: this.currentUserName.toLowerCase(),
                token: sha256(this.currentUserName.toLowerCase() + sha256(this.validateForm.value.currentPassword) + timeDe).toUpperCase(),
                time: timeDe,
                newPwd: sha256(this.validateForm.value.newPassword)
            };
            this.changePasswordBoxService.changePwd(param).subscribe(res => {
                if (res['code'] === '000000') {
                    // 登出
                    this.message.notify({ type: 'info', path: 'UserManagement.ManageUser.change_password.change_success' });
                    this.ls.logOut();
                } else if (res['code'] === '900003') {
                    this.message.notify({ type: 'warning', path: 'UserManagement.ManageUser.change_password.old_password_wrong' });
                } else {
                    this.msg.warning(res['msg']);
                }
            });
        }
    }

    confirmValidator = (control: FormControl): { [s: string]: boolean } => {
        if (!control.value) {
            return { error: true, required: true };
        } else if (control.value !== this.validateForm.controls.newPassword.value) {
            return { isSamePassword: true, error: true };
        }
        return {};
    };
    confirmNewPassword = (control: FormControl): { [s: string]: boolean } => {
        if (!control.value) {
            return { error: true, required: true };
        } else if (control.value === this.validateForm.controls.currentPassword.value) {
            return { isSameWithOldPassword: true, error: true };
        }
        // else if (control.value !== this.validateForm.controls.newPasswordAgain.value) {
        //     return { isSamePassword: true, error: true };
        // }
        return {};
    };
    confirmCurrentPassword = (control: FormControl): { [s: string]: boolean } => {
        if (!control.value) {
            return { error: true, required: true };
        } else if (control.value === this.validateForm.controls.newPassword.value) {
            return { isSameWithOldPassword: true, error: true };
        }
        return {};
    };

    getCaptcha(e: MouseEvent): void {
        e.preventDefault();
    }
    ngOnInit() {
        this.currentUserName = localStorage.getItem('user_name');
        this.validateForm = this.fb.group({
            currentPassword: [null, [this.confirmCurrentPassword]],
            newPassword: [null, [this.confirmNewPassword]],
            newPasswordAgain: [null, [this.confirmValidator]]
        });
    }
    ngOnChanges(changes: SimpleChanges) {}
}
